﻿#include "mainwindow.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"

WindowService::WindowService(int argc, char **argv)
    : QtService<QCoreApplication>(argc, argv, "QtServiceDemo")
{
    setServiceDescription("QtService Demo");
    setServiceFlags(QtServiceBase::CanBeSuspended);


}

WindowService::~WindowService()
{
}

void WindowService::start()
{
    qDebug() << __FUNCTION__;
    //  MainWindow::RegisterDevice();
    //MainWindow w;
}

void WindowService::stop()
{
    qDebug() << __FUNCTION__;
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    udev = udev_new();

    if (!udev) {
        qCritical() << "Failed to initialize udev";
        return;
    }
    // struct udev_enumerate *enumerate=udev_enumerate_new(udev);//1

    //创建监听器
    monitor = udev_monitor_new_from_netlink(udev, "udev");
    //筛选设备
    udev_monitor_filter_add_match_subsystem_devtype(monitor, "block", nullptr);

    //    udev_enumerate_scan_devices(enumerate);//1
    //    struct udev_list_entry *devices=udev_enumerate_get_list_entry(enumerate);//1
    //    struct udev_list_entry *entry;//1
    //    udev_list_entry_foreach(entry,devices){//1
    //        const char *path=udev_list_entry_get_name(entry);//1
    //        struct udev_device *dev=udev_device_new_from_syspath(udev,path);//
    //        const char *syspath=udev_device_get_syspath(dev);//
    //                const char* devicePath = udev_device_get_devnode(dev);//
    //        qDebug()<<syspath;//
    //                qDebug()<<devicePath;//
    //            udev_device_unref(dev);//

    //    }
    //    udev_enumerate_unref(enumerate);//

    udev_monitor_filter_add_match_subsystem_devtype(monitor, "usb", nullptr);
    //启动监视器
    udev_monitor_enable_receiving(monitor);
    //获取监视器文件描述
    int fd = udev_monitor_get_fd(monitor);

    // Use QSocketNotifier to handle udev events in Qt event loop
    notifier = new QSocketNotifier(fd, QSocketNotifier::Read, this);
    connect(notifier, &QSocketNotifier::activated, this, &MainWindow::handleDeviceEvent);


    //将当前工作目录设置为应用程序所在的目录
    QDir::setCurrent(QCoreApplication::applicationDirPath());
    //http.GetClassifcationType();
    //接口映射初始化
    NewSerialportNum=-1;
    IsTerface=false;
    //HeartbeatNum=0;
    myVec.clear();
    TemporaryPath.clear();
    for(int i=0;i<=SYSTEMROW*SYSTEMLIST;++i)
    {
        config.IsUpload[i]=true;
        TemporarytotalSize[i]=0;
        totalSize[i]=0;
        IdentNumber[i]="";
        IdentModel[i]="";
        IsUdisk[i]="";
        //Lastserialnumber[i]="";
        //TemporaryPath[i]="";

        IsInitalize[i]=false;//是否初始化
        IsALLlist[i]=false;//是否重置路径
        IsPriorlize[i]=false;//是否为优先口
        IsExtract[i]=false;
        IsBackdll[i]=-1;
        IsinUpload[i]=true;
        IdentElectricity[i]=0;
    }

    Config_Heavylod();
    InterfaceMapInfo();
    http.GetPlatformInfo();
http.V6ReportClientVersion(config.Version);
    qRegisterMetaType<InterfaceMappingInfo>("InterfaceMappingInfo");
    qRegisterMetaType<DeviceInforMation>("DeviceInforMation");
    //connect(&GlobalSignals::instance(), &GlobalSignals::ThreadRestart, this, &MainWindow::ThreadRestart,Qt::AutoConnection);//打印
    //connect(&GlobalSignals::instance(), &GlobalSignals::Print, this, &MainWindow::handlePrint,Qt::AutoConnection);//打印
    connect(&GlobalSignals::instance(), &GlobalSignals::SendMessageNotifica, this, &MainWindow::SendMessageNotifica,Qt::AutoConnection);//发送消息
    connect(&GlobalSignals::instance(), &GlobalSignals::SendUiMessageNotifica, this, &MainWindow::SendUiMessageNotifica1,Qt::AutoConnection);//发送UI消息
    connect(&GlobalSignals::instance(), &GlobalSignals::SendIMMessageNotifica, this, &MainWindow::SendIMMessageNotifica,Qt::AutoConnection);//发送接口映射消息
    connect(&GlobalSignals::instance(), &GlobalSignals::SendDIMMessageNotifica, this, &MainWindow::SendDIMMessageNotifica,Qt::AutoConnection);//发送设备消息
    connect(&GlobalSignals::instance(), &GlobalSignals::SendPoliceMode, this, &MainWindow::SendPoliceMode,Qt::AutoConnection);//发送部门文件消息
    connect(&GlobalSignals::instance(), &GlobalSignals::ThreadJoin, this, &MainWindow::ThreadJoin,Qt::AutoConnection);//设备配对
    connect(&GlobalSignals::instance(), &GlobalSignals::ThreadUpload, this, &MainWindow::ThreadUpload,Qt::AutoConnection);//普通上传
    connect(&GlobalSignals::instance(), &GlobalSignals::ThreadPriorUpload, this, &MainWindow::ThreadPriorUpload,Qt::AutoConnection);//优先上传
    connect(&GlobalSignals::instance(), &GlobalSignals::ThreadTimer, this, &MainWindow::ThreadTimer,Qt::AutoConnection);//心跳
    connect(&GlobalSignals::instance(), &GlobalSignals::ThreadBandingUpload, this, &MainWindow::ThreadBandingUpload,Qt::AutoConnection);//警情模式上传


    socket=new Socket(config.ServerPor.toUShort());
    //创建线程
    socket->thread = new ThreadPool(2);
    socket->thread->Start("Upload");

    C6Thread = new ThreadPool(1);
    C6Thread->Start("Upload");


    A3Thread= new ThreadPool(2);
    A3Thread->Start("Upload");

    C7Thread= new ThreadPool(10);
    C7Thread->Start("Upload");

    UpThread= new ThreadPool(25);
    UpThread->Start("Upload");

    PUpThread= new ThreadPool(1);
    PUpThread->Start("Upload");
    if(config.Ttime.toInt()!=0)
    {
        //创建定时器
        timer = new QTimer();
        timer->setInterval(config.Ttime.toInt());
        QObject::connect(timer, &QTimer::timeout, [&](){
            socket->thread->PushTask(TNOTICE);//加入线程去请求
        });
        // 启动定时器
        timer->start();
    }

    // 创建定时器
    Threadtimer = new QTimer();
    Threadtimer->setInterval(2000);
    QObject::connect(Threadtimer, &QTimer::timeout, [&](){
        if( C6ThreadTask.size()>=1&&IsC6)
        {
            if(IsExtract[C6ThreadTask.front().serialportnum]==false)
            {
                qDebug()<<"C6";
                C6Thread->PushTask(C6ThreadTask.front());//加入线程去请求

            }
            C6ThreadTask.pop_front();
        }
        //            if( C7ThreadTask.size()>=1&&IsC7)
        //            {
        //                if(IsExtract[C7ThreadTask.front().serialportnum]==false)
        //                {
        //                    qDebug()<<"C6";
        //                    C7Thread->PushTask(C7ThreadTask.front());//加入线程去请求

        //                }
        //                C7ThreadTask.pop_front();
        //            }
        //            if( A3ThreadTask.size()>=1&&Is3A)//T系，R系，3A不能同时转
        //            {
        //                if(IsExtract[A3ThreadTask.front().serialportnum]==false)
        //                {
        //                    qDebug()<<"C6";
        //                    A3Thread->PushTask(A3ThreadTask.front());//加入线程去请求

        //                }
        //                A3ThreadTask.pop_front();
        //            }
        config.WriteInfo(QString("UpThreadTask.size()=%1,UploadNum=%2,UploadRate/60=%3").arg(UpThreadTask.size()).arg(UploadNum).arg(config.UploadRate/60));
        if( UpThreadTask.size()>=1&&UploadNum<config.UploadRate/60)//普通上转线程
        {
            config.WriteInfo(QString("IsExtract[UpThreadTask.front().SerialportNum-100]=%1,config.IsUpload[UpThreadTask.front().SerialportNum-100]=%2，UpThreadTask.front().SerialportNum=%3")
                             .arg(IsExtract[UpThreadTask.front().SerialportNum-100]).arg(config.IsUpload[UpThreadTask.front().SerialportNum-100]).arg(UpThreadTask.front().SerialportNum));
            if(IsExtract[UpThreadTask.front().SerialportNum-100]==false&&config.IsUpload[UpThreadTask.front().SerialportNum-100])
            {
                UpThread->PushTask(UpThreadTask.front());//加入线程去请求

            }
            else if(IsExtract[UpThreadTask.front().SerialportNum-100]==false&&!config.IsUpload[UpThreadTask.front().SerialportNum-100])
            {
                emit GlobalSignals::instance().SendUiMessageNotifica(ACQUISITION_STATION,UPDATE_CONTROL_S,UpThreadTask.front().SerialportNum,"","",UPLOADCOMPLETED,-1);
            }

            UpThreadTask.pop_front();
        }
        if( PUpThreadTask.size()>=1)//优先上传线程
        {
            config.WriteInfo(QString("ThreadUpload,IsExtract=%1,IsUpload=%2").arg(IsExtract[PUpThreadTask.front().SerialportNum-100]).arg(config.IsUpload[PUpThreadTask.front().SerialportNum-100]));

            if(IsExtract[PUpThreadTask.front().SerialportNum-100]==false&&config.IsUpload[PUpThreadTask.front().SerialportNum-100])
            {
                qDebug()<<"PUpThreadTask";
                PUpThread->PushTask(PUpThreadTask.front());//加入线程去请求

            }
            else if(IsExtract[PUpThreadTask.front().SerialportNum-100]==false&&!config.IsUpload[PUpThreadTask.front().SerialportNum-100])
            {
                emit GlobalSignals::instance().SendUiMessageNotifica(ACQUISITION_STATION,UPDATE_CONTROL_S,PUpThreadTask.front().SerialportNum,"","",UPLOADCOMPLETED,-1);
            }

            PUpThreadTask.pop_front();
        }
    });
    Threadtimer->start();

    ThreadUI = new QTimer();
    ThreadUI->setInterval(5000);
    QObject::connect(ThreadUI, &QTimer::timeout, [&](){
        if(UploadNum>0)
        {
            int speed=33;
            switch (UploadNum) {
            case 1:
                speed=30;break;
            case 2:
                speed=25;break;
            default:

                speed=20;break;
            }
            // int speed=12/UploadNum;
            for(int i=1;i<=25;i++)
            {
                if(!IsinUpload[i])
                {
                    if(config.IsPriority!=i&&config.IsPriority>0)
                    {
                        emit GlobalSignals::instance().SendUiMessageNotifica(ACQUISITION_STATION,UPDATE_CONTROL_S,i+100,QString(""),QString(""),UPLOADSTOP,-1);
                    }
                    else
                    {

                        QString folderPath = config.UploadUrl+userNo[i]+"/"+IdentNumber[i]+"_"+Uploadtime[i]; // 替换为你的文件夹路径
                            qInfo()<<"folderPath"<<folderPath;
//                        if(TemporarytotalSize[i]!=0)
//                        {
//                            LastTemporarytotalSize[i]=TemporarytotalSize[i];
//                        }
                        TemporarytotalSize[i]=config.getFolderSize(folderPath);
                          qInfo()<<"TemporarytotalSize[i]"<<TemporarytotalSize[i];
                        TemporarytotalSize[i]=(TemporarytotalSize[i]/1024/1024);
                        if(TemporarytotalSize[i]>=1)
                        {

                            if(TemporarytotalSize[i]>totalSize[i])
                                TemporarytotalSize[i]=totalSize[i];
//                            if(LastTemporarytotalSize[i]!=TemporarytotalSize[i])
//                            {
//                                UploadSchedule[i]=LastTemporarytotalSize[i];
//                            }
qInfo()<<"UploadSchedule[i]"<<UploadSchedule[i];
                            UploadSchedule[i]+=(speed*5);
                            if(UploadSchedule[i]>TemporarytotalSize[i])
                                UploadSchedule[i]=TemporarytotalSize[i];


                            int schedule=((UploadSchedule[i]*1024*1024)/totalSize[i])*100/1024/1024;
                            int scheduletime=(totalSize[i]-UploadSchedule[i])/speed;
                          emit GlobalSignals::instance().SendUiMessageNotifica(ACQUISITION_STATION,UPDATE_CONTROL_S,i+100,QString("%1 s").arg(scheduletime),QString("%1MB/%2MB").arg(UploadSchedule[i]).arg(totalSize[i]),SCHEDULE,schedule);
                        }
                    }

                    //                    QString folderPath = config.UploadUrl+userNo[i]+"/"+IdentNumber[i]+"_"+Uploadtime[i]; // 替换为你的文件夹路径
                    //                    config.WriteInfo(QString("第几个空=%1,folderPath=%2").arg(i).arg(folderPath));
                    //                    TemporarytotalSize[i]=config.getFolderSize(folderPath);
                    //                    config.WriteInfo(QString("TemporarytotalSize[i]=%1,totalSize[i]=%2").arg(TemporarytotalSize[i]).arg(totalSize[i]));
                    //                    if(TemporarytotalSize[i]>=1048576)
                    //                    {
                    //                        config.WriteInfo(QString("TemporarytotalSize[i]=%1,totalSize[i]=%2").arg(TemporarytotalSize[i]).arg(totalSize[i]));
                    //                        int schedule=TemporarytotalSize[i]/totalSize[i]*100/1024/1024;
                    //                        TemporarytotalSize[i]=(TemporarytotalSize[i]/1024/1024);

                    //                        int scheduletime=(totalSize[i]-TemporarytotalSize[i])/speed;
                    //                        config.WriteInfo(QString("i=%1,正在上传目前百分之%2").arg(i).arg(schedule));
                    //                        emit GlobalSignals::instance().SendUiMessageNotifica(ACQUISITION_STATION,UPDATE_CONTROL_S,i+100,QString("%1 s").arg(scheduletime),QString("%1 MB/%2 MB").arg(TemporarytotalSize[i]).arg(totalSize[i]),SCHEDULE,schedule);
                    //                    }
                }
            }
        }
        else
        {
            config.WriteInfo("没有上传中");
        }
    });
    ThreadUI->start();
    // 启动定时器


    // 创建定时器
    sockettimer = new QTimer();
    sockettimer->setInterval(100);
    QObject::connect(sockettimer, &QTimer::timeout, [&](){
        if(Send_List.size()>0)
        {
            socket->Send(Send_List.front().ParentID,Send_List.front().SubID,Send_List.front().jsonObject);
            Send_List.pop_front();
        }
    });
    // 启动定时器
    sockettimer->start();


    // 创建定时器
    Usbtimer = new QTimer();
    Usbtimer->setInterval(5000);
    QObject::connect(Usbtimer, &QTimer::timeout, [&](){
        getUsbInfo();
        for(int i=0;i<myVec.size();i++)
        {
            if(myVec[i].Bus!="")
            {
                auto it = std::find_if(usbInfo.begin(), usbInfo.end(), [&](const UsbInfo Info) {
                    qDebug() <<Info.Bus<<myVec[i].Bus;
                    return (Info.Bus==myVec[i].Bus);
                });

                // If the target element is found, erase itvid from the vector
                if (it != usbInfo.end()) {

                    // 输出提取的值
                    qDebug() <<"存在"<<it->Bus;
                    continue;
                }
                else
                {
                    //                if(myVec[i].serialport!="")
                    //                {
                    config.WriteInfo(QString("磁盘拔出%1").arg(i+1));

                    emit GlobalSignals::instance().SendUiMessageNotifica(ACQUISITION_STATION,UPDATE_CONTROL_S,myVec[i].serialportnum+100,""," ",IDLE,-1);
                    //myVec[i].Bus="";
                    myVec[i].route="";
                    myVec[i].pid="";
                    myVec[i].vid="";
                    myVec[i].serialnumber="";
                    myVec[i].manufacturer="";
                    myVec[i].model="";
                    myVec[i].Device="";
                    myVec[i].Identnumber="";
                    if(config.UpdateRouteValueInfo("config_record.ini",QString("label_%1").arg(i+1),""))
                    {

                        //写入成功
                    }
                    IsUdisk[i+1]="";
                    //IsBackdll[i+1]=-1;
                    IsExtract[i+1]=true;
                    // }
                    continue;
                }
            }
        }
    });
    // 启动定时器
    Usbtimer->start();
    // 获取当前工作目录
    QString currentPath = QDir::currentPath();
    // 获取当前工作目录
    config.WriteInfo(QString("当前路径%1").arg(currentPath));
    QProcess process;
    process.start(QString("sh %1/Delete.sh").arg(currentPath));
    if (!process.waitForFinished()) {
        qDebug() << "Failed to execute df command.";
    }


}

bool MainWindow::Config_Heavylod()
{
    if(!config.ReadInfo("config_label.ini"))
        return false;
    if(!config.ReadInfo("config.ini"))
        return false;

    if( config.Mode=="警情")
    {
        IsWarnInstance=true;
    }
    else
    {
        IsWarnInstance=false;
    }
    row=config.Row.toInt();
    column=config.List.toInt();
    if( config.DeleteFiles=="true")
    {
        IsDeleteFiles=true;
    }
    else
    {
        IsDeleteFiles=false;
    }
    if( config.MaxUploadRate=="")//一个硬盘60MB/s
    {
        return false;
    }
    else
    {
        // 寻找第一个非数字的字符的位置
        int index = 0;
        while (index < config. MaxUploadRate.length() &&  config.MaxUploadRate.at(index).isDigit()) {
            index++;
        }

        // 使用left方法截取数字部分
        QString numericPart =  config.MaxUploadRate.left(index);

        // 将字符串转换为整数
        config.UploadRate = numericPart.toInt();
        if(config.UploadRate<60)
        {
            config.WriteInfo( "Config文件错误") ;
            //    emit GlobalSignals::instance().WriteLog("上传速率小于60");
            return false;
        }
    }

    if( config.prior==""|| config.prior.toInt()<0)
    {
        AppointFirstNum=-1;
    }
    else
    {
        AppointFirstNum= config.prior.toInt();
        //IsPriorlize[AppointFirstNum]=true;
    }
    return true;

}
void MainWindow::handleDeviceEvent(int socket) {

    //  qDebug() << "socket:" << socket;
    struct udev_device* dev = udev_monitor_receive_device(monitor);
    if (dev) {
        const char*subsystem=udev_device_get_subsystem(dev);
        const char* action = udev_device_get_action(dev);
        const char* devicePath = udev_device_get_devnode(dev);

        if (action && devicePath) {
            if (strcmp(action, "add") == 0) {
                //磁盘
                if (strcmp(subsystem, "block") == 0) {
                    qDebug() << "Device block:" << devicePath;

                    const char* syspath = udev_device_get_syspath(dev);
                    const char* devpath = udev_device_get_devpath(dev);

                    qDebug() << "syspath ID:" << (syspath ? syspath : "N/A");
                    qDebug() << "devpath ID:" << (devpath ? devpath : "N/A");


                    DeviceInforMation UsbInfo;

                    QString Mountpath=QString::fromStdString(devicePath);
                    UsbInfo.route=Mountpath;
                    qDebug() << "Mountpath" << Mountpath;
                    config.WriteInfo(QString("Mountpath=%1").arg(Mountpath));
                    QString Device=sys.getDiskSpace(Mountpath);
                    if(Device!="")
                    {
                        UsbInfo.Device=Device;
                        config.WriteInfo(QString("Device%1").arg(Device));
                        int usbPos=QString::fromStdString(syspath).indexOf("/usb");
                        QString Path =QString::fromStdString(syspath).mid(usbPos+4);
                        qDebug() << "Path:" << Path;
                        int Path1=Path.indexOf(':');
                        int Path2=Path.lastIndexOf('/',Path1);
                        Path=Path.mid(Path2+1,Path1-(Path2+1));
                        qDebug() << "Path:" << Path;
                        UsbInfo.serialport=Path;
                        ListeningDisks(UsbInfo);
                    }

                }
                else if (strcmp(subsystem, "usb") == 0) {
                    qDebug() << "Device usb:" << devicePath;
                    // Output device information

                    const char* vendorId = udev_device_get_sysattr_value(dev, "idVendor");
                    const char* productId = udev_device_get_sysattr_value(dev, "idProduct");
                    const char* manufacturer = udev_device_get_sysattr_value(dev, "manufacturer");
                    const char* product = udev_device_get_sysattr_value(dev, "product");
                    const char* serial = udev_device_get_sysattr_value(dev, "serial");
                    const char* syspath = udev_device_get_syspath(dev);
                    const char* devpath = udev_device_get_devpath(dev);

                    // Additional information
                    const char* bus = udev_device_get_sysattr_value(dev, "busnum");
                    const char* device = udev_device_get_sysattr_value(dev, "devnum");

                    qDebug() << "syspath ID:" << (syspath ? syspath : "N/A");
                    qDebug() << "devpath ID:" << (devpath ? devpath : "N/A");
                    qDebug() << "Vendor ID:" << (vendorId ? vendorId : "N/A");
                    qDebug() << "Product ID:" << (productId ? productId : "N/A");

                    qDebug() << "Bus:" << (bus ? bus : "N/A");
                    qDebug() << "Device:" << (device ? device : "N/A");

                    qDebug() << "manufacturer:" << (manufacturer ? manufacturer : "N/A");
                    qDebug() << "product:" << (product ? product : "N/A");
                    qDebug() << "serial:" << (serial ? serial : "N/A");

                    DeviceInforMation UsbInfo;
                    UsbInfo.vid=vendorId;
                    UsbInfo.pid=productId;
                    UsbInfo.serialnumber=serial;
                    UsbInfo.manufacturer=manufacturer;
                    UsbInfo.model=product;
                    UsbInfo.serialport=QString::fromStdString(syspath).section('/',-1);
                    UsbInfo.route=devicePath;
                    UsbInfo.Bus=QString("%1-%2").arg(bus).arg(device);
                    QString Identnumber="112";
                    //TCLC6RotaryTable("sda",Identnumber);
                    ListeningAccess(UsbInfo);
                    //QString Identnumber="1";
                    // TCLC6RotaryTable("DSJ-TCLS1A11310010",Identnumber);
                }

            }
            else if (strcmp(action, "remove") == 0) {
                if (strcmp(subsystem, "block") == 0) {
                    qDebug() << "Device removed:block" << devicePath;

                    const char* syspath = udev_device_get_syspath(dev);
                    const char* devpath = udev_device_get_devpath(dev);


                    qDebug() << "syspath ID:" << (syspath ? syspath : "N/A");
                    qDebug() << "devpath ID:" << (devpath ? devpath : "N/A");
                    int usbPos=QString::fromStdString(syspath).indexOf("/usb");
                    QString Path =QString::fromStdString(syspath).mid(usbPos+4);
                    qDebug() << "Path:" << Path;
                    int Path1=Path.indexOf(':');
                    int Path2=Path.lastIndexOf('/',Path1);
                    Path=Path.mid(Path2+1,Path1-(Path2+1));
                    qDebug() << "Path:" << Path;
                    ListeningUnplug(Path);

                }
                else if (strcmp(subsystem, "usb") == 0) {
                    qDebug() << "Device removed:usb" << devicePath;

                    const char* syspath = udev_device_get_syspath(dev);
                    const char* devpath = udev_device_get_devpath(dev);


                    qDebug() << "syspath ID:" << (syspath ? syspath : "N/A");
                    qDebug() << "devpath ID:" << (devpath ? devpath : "N/A");

                    ListeningUnplug(QString::fromStdString(syspath).section('/',-1));


                }
            }
        }

        udev_device_unref(dev);
    }
}

void MainWindow::SendMessageNotifica(int ParentID, int SubID, int state)
{
    QJsonObject jsonObject;
    jsonObject["state"] = state;
    config.WriteInfo("SendMessageNotifica");
    Send send;
    send.ParentID=ParentID;
    send.SubID=SubID;
    send.jsonObject=jsonObject;
    Send_List.push_back(send);
    //socket->Send(ParentID,SubID,jsonObject);
}
void MainWindow::SendUiMessageNotifica1(int ParentID, int SubID,int SerialportNum, QString Text, QString TextInfo, int Textprompt, int Display)
{
    qDebug()<<"发送";
    QJsonObject jsonObject;
    jsonObject["SerialportNum"] = SerialportNum;
    jsonObject["Text"] = Text;
    jsonObject["TextInfo"] = TextInfo;
    jsonObject["Textprompt"] = Textprompt;
    jsonObject["Display"] = Display;
    config.WriteInfo("SendUiMessageNotifica1");
    Send send;
    send.ParentID=ParentID;
    send.SubID=SubID;
    send.jsonObject=jsonObject;
    Send_List.push_back(send);
    // socket->Send(ParentID,SubID,jsonObject);
}
void MainWindow::SendIMMessageNotifica(int ParentID, int SubID, InterfaceMappingInfo Info)
{
    qDebug()<<"SendIMMessageNotifica";
    QJsonObject jsonObject;
    jsonObject["Indet"] = Info.Indet;
    jsonObject["Row"] = Info.Row;
    jsonObject["Column"] = Info.Column;
    jsonObject["AppointFirst"] = Info.AppointFirst;
    config.WriteInfo("SendIMMessageNotifica");
    Send send;
    send.ParentID=ParentID;
    send.SubID=SubID;
    send.jsonObject=jsonObject;
    Send_List.push_back(send);
    //socket->Send(ParentID,SubID,jsonObject);
}
void MainWindow::SendDIMMessageNotifica(int ParentID, int SubID, DeviceInforMation Info)
{
    QJsonObject jsonObject;
    jsonObject["serialportnum"] = Info.serialportnum;
    jsonObject["vid"] = Info.vid;
    jsonObject["pid"] = Info.pid;
    jsonObject["serialnumber"] = Info.serialnumber;
    jsonObject["manufacturer"] = Info.manufacturer;
    jsonObject["model"] = Info.model;
    jsonObject["route"] = Info.route;
    jsonObject["Device"] = Info.Device;
    config.WriteInfo("SendDIMMessageNotifica");
    Send send;
    send.ParentID=ParentID;
    send.SubID=SubID;
    send.jsonObject=jsonObject;
    Send_List.push_back(send);
    //socket->Send(ParentID,SubID,jsonObject);
}

void MainWindow::SendPoliceMode(int ParentID, int SubID)
{
    QJsonObject jsonObject;
    if(SubID==DEPARTMENT_FILE_QUERY_S)
    {
        QJsonArray jsonunitArray;
        QJsonArray jsoncategoryArray;
        for (int i = 0; i < DepartmentName.size(); ++i) {
            QJsonObject unit_list;
            unit_list["ID"] = DepartmentName[i].ID;
            unit_list["Name"] = DepartmentName[i].Name;
            jsonunitArray.append(unit_list);
        }
        for (int i = 0; i < Filetype.size(); ++i) {
            QJsonObject category_list;
            category_list["ID"] = Filetype[i].ID;
            category_list["Name"] = Filetype[i].Name;
            jsoncategoryArray.append(category_list);
        }
        jsonObject["category_list"] = jsoncategoryArray;
        jsonObject["unit_list"] = jsonunitArray;
        qDebug()<<jsonunitArray;
        qDebug()<<jsoncategoryArray;
    }
    else if(SubID==POLICE_SITUATION_INQUIRY_S)
    {
        QJsonArray jsonPoliceInfo;
        for (int i = 0; i < PoliceInfo.size(); ++i) {
            QJsonObject Police_list;

            Police_list["case_number"] = PoliceInfo[i].case_number;
            Police_list["unit_number"] = PoliceInfo[i].unit_number;
            Police_list["case_desc"] = PoliceInfo[i].case_desc;
            Police_list["happen_address"] = PoliceInfo[i].happen_address;
            Police_list["call_police_time"] = PoliceInfo[i].call_police_time;
            Police_list["alarm_time_text"] = PoliceInfo[i].alarm_time_text;
            Police_list["trafficCaseTable"] = PoliceInfo[i].trafficCaseTable;
            jsonPoliceInfo.append(Police_list);

            jsonObject["jsonPoliceInfo"] = jsonPoliceInfo;
        }

    }

    config.WriteInfo("SendPoliceMode");
    socket->Send(ParentID, SubID, jsonObject);
}
void MainWindow::ThreadTimer(int serialportnum,bool IsStart)
{
    //    config.WriteInfo(QString("ThreadTimer,serialportnum=%1").arg(serialportnum));
    //    if(IsStart)
    //        ThreadUI[serialportnum]->start();
    //    else
    //        ThreadUI[serialportnum]->stop();
}

void MainWindow::ThreadPriorUpload(int serialportnum,QString userID,QString pwd)
{

    if(userID!=""&&pwd!="")
    {
        UploadInfo threadinfo;
        threadinfo.Indet=TUPLOAD;
        threadinfo.UserID=userID;
        threadinfo.Password=pwd;//UserID
        threadinfo.SerialportNum=serialportnum;
        threadinfo.Identnumber=IdentNumber[serialportnum-100];//标识号
        threadinfo.Device=IsUdisk[serialportnum-100];//标识号
        config.WriteInfo(QString("ThreadUpload,threadinfo.Identnumber=%1").arg(threadinfo.Identnumber));

        PUpThreadTask.push_back(threadinfo);
        emit GlobalSignals::instance().SendUiMessageNotifica(ACQUISITION_STATION,UPDATE_CONTROL_S,serialportnum,"",QString("%1;%2;%3;%4").arg(userID).arg(userName[serialportnum-100]).arg(IdentNumber[serialportnum-100]).arg(unitName[serialportnum-100]),UPLOADING,-1);
        //UpThread->PushTask(threadinfo);//加入线程去请求
    }
    else
    {
        UploadInfo threadinfo;
        threadinfo.Indet=AUTOMATIC_TUPLOAD;
        threadinfo.UserID=userID;
        threadinfo.Password=pwd;//UserID
        threadinfo.SerialportNum=serialportnum;
        threadinfo.Identnumber=IdentNumber[serialportnum-100];//标识号
        threadinfo.Device=IsUdisk[serialportnum-100];//标识号
        config.WriteInfo(QString("ThreadUpload,threadinfo.Identnumber=%1").arg(threadinfo.Identnumber));
        PUpThreadTask.push_back(threadinfo);
    }
}
void MainWindow::ThreadUpload(int serialportnum,QString userID,QString pwd)
{

    if(userID!=""&&pwd!="")
    {
        UploadInfo threadinfo;
        threadinfo.Indet=TUPLOAD;
        threadinfo.UserID=userID;
        threadinfo.Password=pwd;//UserID
        threadinfo.SerialportNum=serialportnum;
        threadinfo.Identnumber=IdentNumber[serialportnum-100];//标识号
        threadinfo.Device=IsUdisk[serialportnum-100];//标识号
        config.WriteInfo(QString("ThreadUpload,threadinfo.Identnumber,userid=%1").arg(userID).arg(threadinfo.Identnumber));

        UpThreadTask.push_back(threadinfo);
        emit GlobalSignals::instance().SendUiMessageNotifica(ACQUISITION_STATION,UPDATE_CONTROL_S,serialportnum,"",QString("%1;%2;%3;%4").arg(userID).arg(userName[serialportnum-100]).arg(IdentNumber[serialportnum-100]).arg(unitName[serialportnum-100]),UPLOADING,-1);
        //UpThread->PushTask(threadinfo);//加入线程去请求
    }
    else
    {
        UploadInfo threadinfo;
        threadinfo.Indet=AUTOMATIC_TUPLOAD;
        threadinfo.UserID=userID;
        threadinfo.Password=pwd;//UserID
        threadinfo.SerialportNum=serialportnum;
        threadinfo.Identnumber=IdentNumber[serialportnum-100];//标识号
        threadinfo.Device=IsUdisk[serialportnum-100];//标识号
        config.WriteInfo(QString("ThreadUpload,threadinfo.Identnumber=%1").arg(threadinfo.Identnumber));
        UpThreadTask.push_back(threadinfo);
        config.WriteInfo(QString("ThreadUpload,threadinfo.UpThreadTask.size()=%1").arg(UpThreadTask.size()));
    }
    // }
}
void MainWindow::ThreadBandingUpload(int serialportnum)
{
    if(AppointFirstNum==serialportnum)
    {
        if(IsWarnInstance&&fileallsize[serialportnum]>0&&userNo[serialportnum]!="")
        {
            UploadInfo threadinfo;
            threadinfo.Indet=WARNING_TUPLOAD;
            threadinfo.UserID=userNo[serialportnum];
            threadinfo.SerialportNum=serialportnum;
            threadinfo.Identnumber=IdentNumber[serialportnum];//标识号
            threadinfo.Device=IsUdisk[serialportnum];//标识号
            config.WriteInfo(QString("ThreadBandingUpload,serialportnum=%1，UserID=%2,Device=%3,IdentNumber=%4").arg(serialportnum).arg(threadinfo.UserID).arg(threadinfo.Device).arg(threadinfo.Identnumber));
            UpThreadTask.push_back(threadinfo);
        }
    }
    else
    {
        UploadInfo threadinfo;
        threadinfo.Indet=WARNING_TUPLOAD;
        threadinfo.UserID=userNo[serialportnum];
        threadinfo.SerialportNum=serialportnum;
        threadinfo.Identnumber=IdentNumber[serialportnum];//标识号
        threadinfo.Device=IsUdisk[serialportnum];//标识号
        config.WriteInfo(QString("ThreadBandingUpload:AppointFirstNum,serialportnum=%1，UserID=%2,Device=%3,IdentNumber=%4").arg(serialportnum).arg(threadinfo.UserID).arg(threadinfo.Device).arg(threadinfo.Identnumber));
        PUpThreadTask.push_back(threadinfo);
    }

    QJsonObject jsonObject;
    socket->Send(ACQUISITION_STATION,POLICE_SITUATION_UPLOAD_S,jsonObject);
}
//兼容型号配对
void MainWindow::ThreadJoin(int serialportnum,QString vid ,QString pid,QString serialnumber)
{

    DeviceInforMation InforMation;

    config.WriteInfo(QString("ThreadJoin,serialportnum=%1").arg(serialportnum));
    InforMation.serialportnum=serialportnum;
    InforMation.vid=vid;//序列号
    InforMation.pid=pid;
    InforMation.serialnumber=serialnumber;
    InforMation.manufacturer="";
    InforMation.model="";
    InforMation.route="";
    InforMation.Device="";//盘符
    InforMation.Identnumber="";
    //  // threadinfo.message=nullptr;//公告文本
    IdentNumber[serialportnum]=="";
    if(vid=="1BBB"&&pid=="AF2E")
    {
        //         InforMation.Indet=THREADTC7;
        //        //threadinfo.Indet=THREADC6;
        //        C7ThreadTask.push_back(InforMation);

        //        C7Thread->PushTask(C7ThreadTask.front());//加入线程去请求
        //         C7ThreadTask.pop_front();

        //        if(IsC7==false)
        //        {
        //            qInfo()<<"IsC7";
        //            C7Thread->a();
        //            C7Thread->Threadincrease(1);
        //            C7Thread->Start("Upload");
        //            //ThreadRestart(1);
        //        }
        //        if(IsC7)
        //        {
        InforMation.Indet=THREADC7;
        C7ThreadTask.push_back(InforMation);

        //}

    }
    else if((vid=="0E8D"&&pid=="201C")||(vid=="0e8d"&&pid=="201c"))
    {
        InforMation.Indet=THREADC6;
        //threadinfo.Indet=THREADC6;
        C6ThreadTask.push_back(InforMation);
        //threadPool_C8->PushTask(threadinfo);

    }
    else if(vid=="18D1"&&pid=="4EE7")
    {
        InforMation.Indet=THREADC6;
        //threadinfo.Indet=THREADC6;
        C6ThreadTask.push_back(InforMation);
        // threadPool_C8->PushTask(threadinfo);
    }
    else if(vid=="1782"&&pid=="4012")
    {
        InforMation.Indet=THREADC6;
        //threadinfo.Indet=THREADC6;
        C6ThreadTask.push_back(InforMation);
        // threadPool_C8->PushTask(threadinfo);
    }
    else if(vid=="4255"&&pid=="0001"/*&&(serialnumber.contains("TCLT6")||serialnumber.contains("TCLT5"))*/)
    {
        //        InforMation.Indet=THREADT6;
        //        //threadinfo.Indet=THREADC6;
        //        T6ThreadTask.push_back(InforMation);

        //        T6Thread->PushTask(T6ThreadTask.front());//加入线程去请求
        //        T6ThreadTask.pop_front();

        InforMation.Indet=THREAD3A;
        //threadinfo.Indet=THREADC6;
        A3ThreadTask.push_back(InforMation);


        //        InforMation.Indet=THREADR1;
        //        //threadinfo.Indet=THREADC6;
        //        R1ThreadTask.push_back(InforMation);
        //        A3Thread->PushTask(A3ThreadTask.front());//加入线程去请求
        //        A3ThreadTask.pop_front();
        // threadPool_C8->PushTask(threadinfo);
    }

    //    else if(vid=="4255"&&pid=="0001")
    //    {
    //         InforMation.Indet=THREADR1;
    //        //threadinfo.Indet=THREADC6;
    //        R1ThreadTask.push_back(InforMation);

    //        R1Thread->PushTask(R1ThreadTask.front());//加入线程去请求
    //         R1ThreadTask.pop_front();
    //        // threadPool_C8->PushTask(threadinfo);
    //    }
    return;
}

MainWindow::~MainWindow()
{
    udev_unref(udev);
    delete ui;
}

